//
//  File.swift
//  baidu_map_plugin
//
//  Created by CTI on 2021/1/28.
//

import UIKit
import CTIMapView
import BaiduMapAPI_Utils
import BaiduMapAPI_Map

class BadiduMapView : NSObject,FlutterPlatformView {
    
    var frame:CGRect
    var baiduMapView:UIView!
    var mapView:BaiduMapView?
    var _channel: FlutterMethodChannel
    var markers: [MarkerModel] = []
    
    init(frame:CGRect,viewId: Int64,messenger: FlutterBinaryMessenger) {
        _channel = FlutterMethodChannel(name: "plugins.baidumapplugin_example/mapview_\(viewId)", binaryMessenger: messenger)
        self.frame = frame
        super.init()
        baiduMapView = UIView(frame:frame)
        _channel.setMethodCallHandler {[unowned self] (call, result)  in
            self.handler(call, result: result)
        }
    }
    
    func handler(_ call: FlutterMethodCall, result: FlutterResult) {
        if  call.method == "updateMapView" {
            if markers.count != 0 {
                /// 先清除全部的路点
                mapView?.removeAllAnnotations()
                markers.removeAll()
            }

            /// 添加多个marker
            print("添加多个marker")
            let data = call.arguments as? String
            var markers: [String: Any]? = nil
            markers = decodeStringToDictionary(string: data)

            guard let resultMarkers = markers else {
                return
            }

            let options = resultMarkers["overlayOptions"] as? [[String: Any]?]
            guard let optionsData = options else {
                return
            }

            for item in optionsData.enumerated() {
                if let itemModel = item.element {
                    if item.offset == 0 {
                        setMapCenter(item: itemModel)
                    }
                    addMarker(data: itemModel,offset: item.offset)
                }
            }
        }else if call.method == "setMapViewCenter" {
            /// 设置中心
            if let data = call.arguments as? [String: Any] {
                setMapCenter(item: data)
            }
        }
      
    }
    
    func addMarker(data: [String: Any],offset: Int) {
        print("添加maker")
        
        let model = MarkerModel.fromJson(jsonData: data)
        markers.append(model)
        
        let location =  BMKCoordTrans(CLLocationCoordinate2D(latitude: model.latitude, longitude: model.longitude), .COORDTYPE_GPS, .COORDTYPE_BD09LL)
        mapView?.addAnnotation(coordinate: location, id: model.id, title: model.text, selected: model.isSelect)
    }
    
    func setMapCenter(item: [String:Any]){
        let latitude = item["latitude"] as? Double
        let longitude = item["longitude"] as? Double
        
        let location =  BMKCoordTrans(CLLocationCoordinate2D(latitude: latitude ?? 0.0, longitude: longitude ?? 0.0), .COORDTYPE_GPS, .COORDTYPE_BD09LL)
        mapView?.setCenter(location: location, animated: true)
        
    }
    
    func view() -> UIView {
        baiduMapView.backgroundColor = UIColor.white
        
        if mapView == nil {
            mapView = BaiduMapView(CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight))
            mapView?.delegate = self
            if let map = mapView?.getMapView() {
                baiduMapView.addSubview(map)
            }
        }else {
            if let map = mapView?.getMapView() {
                map.frame = baiduMapView.bounds
            }
        }
        
        return baiduMapView
    }
    
    func decodeStringToDictionary(string: String?) -> [String: Any]? {
        let jsonData = string?.data(using: .utf8)
        if let result = jsonData {
            let dic = try? JSONSerialization.jsonObject(with: result, options: .mutableContainers)
            return dic as? [String: Any]
        }
        return nil
    }
    
    deinit {
//        NSLog("---baiduMapView卸载-----")
    }
}

extension BadiduMapView: BaiduMapViewDelegateProtocol {
    public func didSelectAnnotaion(id: String, isSelected: Bool) {
        NSLog("点击了%@--状态为-%d", id,isSelected)
        if  let model = markers.first(where: { (item) -> Bool in
            item.id == id
        }) {
            model.isSelect = isSelected
//            let jsonStr = model.toJson()
            _channel.invokeMethod("onSelectedOverlay", arguments: model.toJson())
      }
    }
}


class BadiduMapViewFactory: NSObject,FlutterPlatformViewFactory {
    var messenger: FlutterBinaryMessenger
    
    init(messenger: FlutterBinaryMessenger) {
        self.messenger = messenger
    }

    func create(withFrame frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any?) -> FlutterPlatformView {
        let view = BadiduMapView(frame: frame,viewId: viewId, messenger: self.messenger)
        return view;
    }
    
    deinit {
//        NSLog("BadiduMapViewFactory释放")
    }
}


